import { Injectable, Inject, forwardRef } from '@nestjs/common';
import { ResponseUtil } from '../common/utils/response.util'; 
import { WebsocketGateway } from '../websocket/websocket.gateway';

@Injectable()
export class LogService {
   public logData:string = ""
   private interval: NodeJS.Timeout;
   constructor(@Inject(forwardRef(() => WebsocketGateway)) private websocketGateway: WebsocketGateway) {}
  
  //根据部署文件ID节点ID获取日志全量数据
  async getLogData(body:any) {
    const { deploymentId, nodeId } = body
    this.logData = Array.from({length:1},(_,i)=>{
      return `${deploymentId}-${nodeId}-${new Date().getTime()+i}\n`
    }).join('')
    const logData = {
      deploymentId,
      nodeId,
      outPut: this.logData
    }
    // 启动WebSocket推送后续日志
    this.startPushingLogUpdates(deploymentId, nodeId);  
    return ResponseUtil.success(logData, 'Get log data');
  }

  // 生成单行模拟日志数据
  generateLogLine(deploymentId: string, nodeId: string): string {
    const timestamp = new Date().toISOString();
    const randomActions = ['INFO', 'WARN', 'DEBUG', 'ERROR'];
    const randomAction = randomActions[Math.floor(Math.random() * randomActions.length)];
    return `[${timestamp}] [${randomAction}] [${deploymentId}] [${nodeId}]: 模拟日志内容-${Math.floor(Math.random() * 1000)}\n`;
  }
  
  // 开始推送增量日志更新
  private startPushingLogUpdates(deploymentId: string, nodeId: string) {
    // 每隔2秒推送一次模拟的日志更新
    this.interval&&clearInterval(this.interval)
    this.interval = setInterval(() => {
      const newLogLine ='濡傛灉鎴戞槸DJ,浣犱細鐖辨垜鍚�?/n';     
      // 通过WebsocketGateway推送日志更新
      this.websocketGateway.broadcastLogUpdate(deploymentId, nodeId, newLogLine);
      // 模拟30秒后停止推送
      setTimeout(() => {
        // clearInterval(interval);
        console.log(`Stopped pushing logs for deployment: ${deploymentId}, node: ${nodeId}`);
      }, 30000);
    }, 5000);
  }

  // 停止推送日志
  stopPushingLogUpdates() {
    clearInterval(this.interval);
  }
}
